package com.eliza.music.model.vm

import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.eliza.music.model.dao.SongDao
import com.eliza.music.model.entity.Song
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject


@HiltViewModel
class PlayingMusicVm @Inject constructor(val songDao: SongDao) : ViewModel() {

    private val _songs = MutableStateFlow<List<Song>>(emptyList())
    val songs: StateFlow<List<Song>> = _songs

    init {
        viewModelScope.launch {
            _songs.value = songDao.getAll()
        }
    }

    private var currentIndex = 0
    val currentSong = mutableStateOf<Song>(
        if (songs.value.isNotEmpty()) {
            songs.value.first()
        } else {
            Song()
        }
    )

    fun setSongs(list: List<Song>) {
        _songs.value = list
        viewModelScope.launch {
            songDao.insert(list)
        }
    }

    fun nextSong() {
        currentIndex++
        currentSong.value = _songs.value.get(currentIndex)
    }

    fun preSong() {
        currentIndex--
        if (currentIndex < 0) {
            currentIndex = 0
            currentSong.value = _songs.value.get(currentIndex)
        }
    }
}